<template>
  <div>
	<el-form
		ref="connectionFormRef"
		:model="formData"
		:rules="formRules"
		label-width="120px"
		label-position="top"
	>   
		<el-form-item label="请求地址" prop="url">
			<el-input
			  v-model="formData.url"
			  placeholder="请输入请求网址"
			  class="input-with-select"
			>
			</el-input>
		</el-form-item> 
		<el-row :gutter="20">
		  <el-col :span="12">
			<el-form-item label="请求方法" prop="method">
				<el-select
				  v-model="formData.method"
				  placeholder="请选择请求方法"
				  style="width: 100%;"
				>
				  <el-option label="GET" value="GET" />
				  <el-option label="POST" value="POST" />
				  <el-option label="PUT" value="PUT" />
				  <el-option label="DELETE" value="DELETE" />
				  <el-option label="PATCH" value="PATCH" />
				  <el-option label="HEAD" value="HEAD" />
				  <el-option label="OPTIONS" value="OPTIONS" />
				</el-select>
			</el-form-item>
		  </el-col>
		  <el-col :span="12">
			<el-form-item prop="timeout" label="超时时间">
			  <el-input v-model="formData.timeout" placeholder="请输入超时时间" type="number" :min="10" >
				<template #append>毫秒</template>
			  </el-input>
			</el-form-item>
		  </el-col>
		</el-row>
	</el-form>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import {HttpConnectionField} from '@/components/DataWorkflow/types/data-collect.ts';
import { ref,watch} from 'vue-demi';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { reactive } from 'vue-demi';

const props = defineProps<{ 
  data: HttpConnectionField
}>();

const connectionFormRef=ref<FormInstance>();
const formRules = reactive<FormRules>({
	url: [
		{ required: true, message: '请输入接口名称', trigger: 'blur' },
		{ min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' },
		{ 
			validator: (_, value, callback) => {
		        if (!value) {
		          callback(new Error('请输入请求地址'))
		        } else if (!/^https?:\/\//i.test(value)) {
		          callback(new Error('请输入有效的HTTP/HTTPS地址'))
		        } else {
		          callback()
		        }
			},
			trigger: 'blur'
		}
	],
	method: [
		{ required: true, message: '请选择接口请求类型', trigger: 'blur' }
	],
	timeout: [
		{ required: true, message: '请输入超时时间', trigger: 'blur' }
	]
});

const formData = ref<HttpConnectionField>({ ...props.data })

watch(() => props.data, (val: HttpConnectionField) => {
  formData.value = val || {};
}, { immediate: true, deep: true });

const validate = async (): Promise<boolean> => {
  if (!connectionFormRef.value) return false
  try {
    await connectionFormRef.value.validate()
    return true
  } catch {
    return false
  }
}

defineExpose({
  validate
})

</script>

<style>
</style>